import { Model, DataTypes, Sequelize, Optional } from 'sequelize';
import { sequelize } from '../config/database';
import User from './User';
import InterestTag from './InterestTag';

interface CircleAttributes {
    id: string;
    name: string;
    description: string;
    creatorId: string;
    coverImage?: string | null;
    memberCount: number;
    postCount: number;
    isPrivate: boolean;
    createdAt?: Date;
    updatedAt?: Date;
}

interface CircleCreationAttributes extends Optional<CircleAttributes, 'id' | 'createdAt' | 'updatedAt' | 'coverImage' | 'memberCount' | 'postCount' | 'isPrivate'> { }

export class Circle extends Model<CircleAttributes, CircleCreationAttributes> implements CircleAttributes {
    public id!: string;
    public name!: string;
    public description!: string;
    public creatorId!: string;
    public coverImage!: string;
    public memberCount!: number;
    public postCount!: number;
    public isPrivate!: boolean;
    public readonly createdAt!: Date;
    public readonly updatedAt!: Date;

    // 关联方法
    public async setTags(tagIds: string[], options?: any): Promise<void> {
        await this.setTags(tagIds, options);
    }

    public async addMember(userId: string, options?: any): Promise<[User, boolean]> {
        return await this.addMember(userId, options);
    }

    public async removeMember(userId: string): Promise<void> {
        await this.removeMember(userId);
    }

    public async getMembers(options?: any): Promise<User[]> {
        return await this.getMembers(options);
    }

    public async hasMember(userId: string): Promise<boolean> {
        const members = await this.getMembers({ where: { id: userId } });
        return members.length > 0;
    }

    public static associate(models: {
        User: typeof User;
        CirclePost: typeof import('./CirclePost').CirclePost;
        CircleComment: typeof import('./CircleComment').CircleComment;
    }) {
        Circle.belongsTo(models.User, { as: 'creator', foreignKey: 'creatorId' });
        Circle.belongsToMany(models.User, {
            through: 'CircleMember',
            as: 'members',
            foreignKey: 'circleId',
            otherKey: 'userId',
        });
    }

    public async countMembers(): Promise<number> {
        const count = await sequelize.models.CircleMember.count({
            where: { circleId: this.id }
        });
        return count;
    }
}

export const initCircle = (sequelize: Sequelize) => {
    Circle.init(
        {
            id: {
                type: DataTypes.UUID,
                defaultValue: DataTypes.UUIDV4,
                primaryKey: true,
            },
            name: {
                type: DataTypes.STRING,
                allowNull: false,
                unique: true,
            },
            description: {
                type: DataTypes.TEXT,
                allowNull: false,
            },
            creatorId: {
                type: DataTypes.UUID,
                allowNull: false,
                references: {
                    model: User,
                    key: 'id',
                },
            },
            coverImage: {
                type: DataTypes.STRING,
                allowNull: true,
            },
            memberCount: {
                type: DataTypes.INTEGER,
                allowNull: false,
                defaultValue: 0,
            },
            postCount: {
                type: DataTypes.INTEGER,
                allowNull: false,
                defaultValue: 0,
            },
            isPrivate: {
                type: DataTypes.BOOLEAN,
                allowNull: false,
                defaultValue: false,
            },
        },
        {
            sequelize,
            tableName: 'circles',
            timestamps: true,
        }
    );
};

// 创建圈子-标签关联表
export const initCircleTag = (sequelize: Sequelize) => {
    const CircleTag = sequelize.define('CircleTag', {
        id: {
            type: DataTypes.UUID,
            defaultValue: DataTypes.UUIDV4,
            primaryKey: true,
        },
        circleId: {
            type: DataTypes.UUID,
            allowNull: false,
            references: {
                model: Circle,
                key: 'id',
            },
        },
        tagId: {
            type: DataTypes.UUID,
            allowNull: false,
            references: {
                model: InterestTag,
                key: 'id',
            },
        },
    }, {
        tableName: 'circle_tags',
        timestamps: true,
        indexes: [
            {
                unique: true,
                fields: ['circleId', 'tagId'],
            },
        ],
    });

    return CircleTag;
};

// 创建圈子-成员关联表
export const initCircleMember = (sequelize: Sequelize) => {
    const CircleMember = sequelize.define('CircleMember', {
        id: {
            type: DataTypes.UUID,
            defaultValue: DataTypes.UUIDV4,
            primaryKey: true,
        },
        circleId: {
            type: DataTypes.UUID,
            allowNull: false,
            references: {
                model: Circle,
                key: 'id',
            },
        },
        userId: {
            type: DataTypes.UUID,
            allowNull: false,
            references: {
                model: User,
                key: 'id',
            },
        },
        role: {
            type: DataTypes.ENUM('admin', 'moderator', 'member'),
            allowNull: false,
            defaultValue: 'member',
        },
        status: {
            type: DataTypes.ENUM('pending', 'accepted', 'rejected'),
            allowNull: false,
            defaultValue: 'pending',
        },
    }, {
        tableName: 'circle_members',
        timestamps: true,
        indexes: [
            {
                unique: true,
                fields: ['circleId', 'userId'],
            },
        ],
    });

    return CircleMember;
};

export default Circle;